package com.example.easytts.controller

import com.example.easytts.service.MemberDailyLimitExceededException
import com.example.easytts.service.IpDailyLimitExceededException
import com.example.easytts.service.OcrDailyLimitExceededException
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.security.access.AccessDeniedException

data class ErrorResponse(val code: Int, val message: String)

@ControllerAdvice
class GlobalExceptionHandler {
    @ExceptionHandler(Exception::class)
    fun handleGenericException(ex: Exception): ResponseEntity<ErrorResponse> {
        return ResponseEntity
            .status(HttpStatus.INTERNAL_SERVER_ERROR)
            .body(ErrorResponse(500, "服务器内部错误: ${ex.message}"))
    }

    @ExceptionHandler(AccessDeniedException::class)
    fun handleAccessDenied(ex: AccessDeniedException): ResponseEntity<ErrorResponse> {
        return ResponseEntity
            .status(HttpStatus.FORBIDDEN)
            .body(ErrorResponse(403, "访问被拒绝: ${ex.message}"))
    }

    @ExceptionHandler(IpDailyLimitExceededException::class)
    fun handleIpLimitExceeded(ex: IpDailyLimitExceededException): ResponseEntity<ErrorResponse> {
        return ResponseEntity
            .status(HttpStatus.TOO_MANY_REQUESTS)
            .body(ErrorResponse(42901, ex.message ?: "超出免费字数限制"))
    }

    @ExceptionHandler(MemberDailyLimitExceededException::class)
    fun handleMemberLimitExceeded(ex: MemberDailyLimitExceededException): ResponseEntity<ErrorResponse> {
        return ResponseEntity
            .status(HttpStatus.TOO_MANY_REQUESTS)
            .body(ErrorResponse(42902, ex.message ?: "超出会员每日字数限制"))
    }

    @ExceptionHandler(OcrDailyLimitExceededException::class)
    fun handleOcrLimitExceeded(ex: OcrDailyLimitExceededException): ResponseEntity<ErrorResponse> {
        return ResponseEntity
            .status(HttpStatus.TOO_MANY_REQUESTS)
            .body(ErrorResponse(42903, ex.message ?: "超出每日图片识别次数限制"))
    }
} 